//
//  SLswift
//  Emotion
//
//  Created by lirenqiang on 16/6/2.
//  Copyright © 2016年 lirenqiang. All rights reserved.
//

import UIKit

class SLTextView: UITextView {
    
    func inserEmoticon(em: SLEmoticon) {
        //如果点击的是空白
        if em.isEmpty {
            return
        }
        
        //如果点击的是删除按钮
        if em.isDelete {
            //执行回删
            deleteBackward()
            return 
        }
        
        //点击的是emoji表情
        if em.emoji != nil {
            //替换字符串到对应的光标下
            replaceRange(selectedTextRange!, withText: em.emoji ?? "")
            
            return
        }
        
        //程序走到这个地方  以为用户点击的是  表情图片.
        //实现图文混排,依靠属性字符串
        //1. 获取附件对象
        let attachment = SLTextAttachment()
        
        //2. 给附件对象添加图片
        attachment.image = UIImage(contentsOfFile: em.imagePath ?? "")
        
        //设置文本
        attachment.chs = em.chs
        
        let lineHeight = font?.lineHeight ?? 0
        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        //3. 通过附件对象 实例化属性字符串
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        //3.3 给属性文本添加font属性  但是不可变属性文本不能添加属性的
        imageText.addAttributes([NSFontAttributeName : font!], range: NSMakeRange(0, 1))
        
        //4. 将attributedText转换为可变的属性
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //5.1 在替换之前 记录光标所在位置
        let range = selectedRange
        
        //5.2 替换属性文本
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //6. 重新设置attributedText 
        attributedText = strM
        
        //7. 恢复光标的位置
        selectedRange = NSMakeRange(range.location+1, 0)

    }
    
    func fullText() -> String {
        let attr = self.attributedText
        var strM = String()
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) in
            //            print(dict)
            //            print("--------")
            //            print(range)
            
            if let attachment = dict["NSAttachment"] as? SLTextAttachment {
                
                //图片属性文本
                //如何从附件对象中提取表情图片对应的文字
                strM += (attachment.chs ?? "")
                
            } else {
                //正常的属性文本
                let subStr = (self.text as NSString).substringWithRange(range)
                strM += subStr
            }
            
            
        }
        return strM
    }
    

}

































